package controllers;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.User;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import service.HibernateUtil;
import service.UserDao;

public class UserController extends HttpServlet {

    private HibernateUtil HU = new HibernateUtil();
    private Session sessie = HU.openSession();
    private UserDao ud = new UserDao(sessie);
    private static String titleNew = "New user";
    //private static String titleEdit = "Edit course";

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        if (request.getParameter("teacherID") != null) {
            Long id = Long.parseLong(request.getParameter("teacherID"));

            User user = ud.get(id);
            request.setAttribute("chosenTeacher", user);

            forward(request, response, null, "admin.jsp");

        } else if (request.getParameter("studentID") != null) {
            Long id = Long.parseLong(request.getParameter("studentID"));

            User user = ud.get(id);
            request.setAttribute("chosenStudent", user);

            forward(request, response, null, "admin.jsp");
        } else {
            Locale list[] = SimpleDateFormat.getAvailableLocales();
            List<Locale> localeList = Arrays.asList(list);
            Collections.sort(localeList, new Comparator<Locale>() {

                public int compare(Locale l1, Locale l2) {
                    return l1.getDisplayCountry().compareToIgnoreCase(l2.getDisplayCountry());
                }
            });
            //System.out.println("country: " +list[0].getDisplayLanguage());
            request.setAttribute("countries", localeList);
            forward(request, response, titleNew, "register.jsp");
        }

    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        if (request.getParameter("reset") != null) { //resetten van gebruiker
            Long id = Long.parseLong(request.getParameter("reset"));
            User user = ud.get(id);
            String newPassword = user.getFirstName().substring(0, 2) + user.getLastName();
            user.setPassWord(newPassword);
            ud.update(user);
            EmailController emailControl = new EmailController();
            emailControl.sendEmail(user.getEmail(), "<h2>Password reset Three2Learn</h2>"
                    + "<p>Your password has been reset."
                    + "You can now log in with the given username and password.<p>"
                    + "<p>Your username: " + user.getUserName()
                    + "</br> Your password: " + newPassword + "</p>", "Password reset");
            forward(request, response, null, "admin");
        } else if (request.getParameter("delete") != null) { //deleten van gebruiker
            Long id = Long.parseLong(request.getParameter("delete"));
            User user = ud.get(id);
            ud.delete(user);
            forward(request, response, null, "admin");
        } else { //else aanmaken of updaten user

            long id = 0;
            String firstName = "";
            String lastName = "";
            Date birthDate = new Date();
            String address = "";
            String zipCode = "";
            String city = "";
            String gender = "";
            String phoneNumber = "";
            String email = "";
            String country = "";
            String userName = "";
            String passWord = "";
            boolean empty = false;

            if (request.getParameter("country") != null) {
                country = request.getParameter("country");
                System.out.println("country: " + country);
            }

            if (request.getParameter("firstname") != null) {
                firstName = request.getParameter("firstname");
            } else {
                empty = true;
            }
            if (request.getParameter("lastname") != null) {
                lastName = request.getParameter("lastname");
            } else {
                empty = true;
            }
            if (request.getParameter("email") != null) {
                email = request.getParameter("email");
            } else {
                empty = true;
            }
            if (request.getParameter("username") != null) {
                userName = request.getParameter("username");
            } else {
                empty = true;
            }
            if (request.getParameter("password") != null) {
                passWord = request.getParameter("password");
            }
            if (request.getParameter("birthdate") != null) {
                try {
                    String str_date = request.getParameter("birthdate");
                    DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
                    birthDate = (Date) formatter.parse(str_date);
                } catch (ParseException ex) {
                    Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if ((request.getParameter("street") != null) && (request.getParameter("number") != null)) {
                address = request.getParameter("street") + request.getParameter("number");
            }
            if (request.getParameter("zipcode") != null) {
                zipCode = request.getParameter("zipcode");
            }
            if (request.getParameter("city") != null) {
                city = request.getParameter("city");
            }
            if (request.getParameter("country") != null) {
                country = request.getParameter("country");
            }
            if (request.getParameter("phonenumber") != null) {
                phoneNumber = request.getParameter("phonenumber");
            }
            if (request.getParameter("gender") != null) {
                gender = request.getParameter("gender");
            }

            HttpSession session = request.getSession();
            long uniqueID = System.nanoTime();
            String bankNumber = "";

            if ("true".equals(request.getParameter("admin"))) {
                if (request.getParameter("id") != null) { //update student of teacher
                    //System.out.println("LANANAANANANANAAN" + empty);
                    if (empty != true) {

                        id = Long.parseLong(request.getParameter("id"));
                        User user = ud.get(id);
                        user.setFirstName(firstName);
                        user.setLastName(lastName);
                        user.setUserName(userName);
                        user.setEmail(email);
                        user.setCountry(country);
                        user.setStatus(request.getParameter("status"));
                        ud.update(user);
                    }
                    //forward(request, response, null, "admin");
                    response.sendRedirect("/admin");

                } else {
                    User user = new User();
                    user.setFirstName(firstName);
                    user.setLastName(lastName);
                    user.setUserName(userName);
                    user.setCountry(country);
                    String password = firstName.substring(0, 2) + lastName;
                    user.setPassWord(password); //automatically generate user name
                    user.setEmail(email);
                    user.setStatus(request.getParameter("status"));
                    ud.save(user);
                    EmailController emailControl = new EmailController();
                    emailControl.sendEmail(email, "<h2>Welcome to Three2Learn!</h2>"
                            + "<p>You've succesfully created an account on Three2Learn."
                            + "You can now sign up for any course that may interest you.<p>"
                            + "<p>Your username: " + userName
                            + "</br> Your password: " + password + "</p>", "New Account");
                    //forward(request, response, null, "admin.jsp");
                    response.sendRedirect("/admin");
                }
            } else {

                User user = new User(uniqueID, firstName, lastName, address, zipCode, city, birthDate, gender, phoneNumber, country, "Student", email, userName, passWord);
                ud.save(user);
                String language = models.Bean.getLanguage();
                if (language.equals("nl")) {
                    EmailController emailControl = new EmailController();
                    emailControl.sendEmail(email, "<h2>Welkom bij Three2Learn!</h2>"
                            + "<p>Je hebt succesvol een account aangemaakt bij ons."
                            + "Je kan je nu aanmelden voor elke cursus die je maar wilt.<p>"
                            + "<p>Je gebruikersnaam: " + userName
                            + "</br> Je wachtwoord: " + passWord + "</p>", "Nieuw Account");
                    request.setAttribute("melding", "Je account is gemaakt. Je bent nu in staat om in te loggen!");
                } else {
                    EmailController emailControl = new EmailController();
                    emailControl.sendEmail(email, "<h2>Welcome to Three2Learn!</h2>"
                            + "<p>You've succesfully created an account on Three2Learn."
                            + "You can now sign up for any course that may interest you.<p>"
                            + "<p>Your username: " + userName
                            + "</br> Your password: " + passWord + "</p>", "New Account");
                    request.setAttribute("melding", "Your account has been succesfully made! You can now log in.");
                }
                // response.sendRedirect("/");
                forward(request, response, null, "register.jsp");
            }
        }
    }

    private void forward(HttpServletRequest request, HttpServletResponse response, String titel, String url)
            throws ServletException, IOException {

        request.setAttribute("pageTitle", titel);

        String address = "/" + url;
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }
}
